package com.ff.kvm.service.impl;

import com.ff.kvm.common.third_util.WXPayUtil;
import com.ff.kvm.common.third_util.WXPublicUtil;
import com.ff.kvm.common.util.ConvertUtil;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.mall.consumer.SpreadConsumer;
import com.ff.kvm.service.SpreadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Service
public class SpreadServiceImpl implements SpreadService {

    private final Logger log = LoggerFactory.getLogger(getClass());


    @Autowired
    private SpreadConsumer spreadConsumer;

    @Override
    public Response<String> spreadQRCode(int userId) {

        return spreadConsumer.spreadQRCode(userId);
    }

    @Override
    public void spread(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out = null;
        try {
            out = response.getWriter();

//            //第一次校验token
//            out.write(request.getParameter("echostr"));

            //校验token
            if(!WXPublicUtil.checkSignature(request.getParameter("signature"),request.getParameter("timestamp"),request.getParameter("nonce"))){
                log.info("推广预注册签名校验失败返回");
                return;
            }
            String xml = WXPayUtil.getContent(request.getInputStream(),"UTF-8");
            //只处理扫码关注事件
            if(!xml.contains("<Event><![CDATA[subscribe]]></Event>")){
                return;
            }
            Map<String,String> params = ConvertUtil.xmlToMap(xml);
            String openId = params.get("FromUserName");//扫码的人
            String pollCode = params.get("EventKey").split("qrscene_")[1];
            Response<Boolean> rep = spreadConsumer.spread(pollCode,openId);
            if(!rep.getData()){
                log.info("推广预注册失败pollCode:{},openId:{},",pollCode,openId);
            }
            log.info("推广预注册成功pollCode:{},openId:{},",pollCode,openId);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(out != null){
                out.close();
            }
        }


    }
}
